<template>
  <div>
    <BasicModal
      @register="register"
      title="额度分配"
      width="600px"
      :destroyOnClose="true"
      :canFullscreen="false"
      :showOkBtn="false"
      :showCancelBtn="false"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { ref } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { AssignPackage, QueryOrderList, ConvertibleSkus } from '@/api/phoneAuth/phoneAuthList';
  import { IAssignPackageData } from '@/api/phoneAuth/phoneAuthList/type';

  const { createMessage } = useMessage();

  const emit = defineEmits(['reload']);

  const form = ref<IAssignPackageData>({
    orderId: '',
    skuId: '',
    tenantId: '',
    allotment: 0,
    remark: '',
  });

  const residue = ref(0);

  const [registerForm, { validate, setProps, setFieldsValue, updateSchema }] = useForm({
    schemas: [
      {
        field: 'tenantId',
        component: 'Input',
        label: '字典主键',
        show: false,
      },
      {
        field: 'orgName',
        component: 'Input',
        label: '额度分配机构',
        componentProps: { disabled: true },
      },
      {
        field: 'allotmentTotal',
        component: 'Input',
        label: '平台可配总额',
        componentProps: { disabled: true },
      },
      {
        field: 'effective',
        component: 'Input',
        label: '机构可用额度',
        componentProps: { disabled: true },
      },
      {
        field: 'orderId',
        component: 'Select',
        label: '额度来源订单',
        required: true,
      },
      {
        field: 'skuId',
        component: 'Select',
        label: '分配额度',
        required: true,
        componentProps: {
          placeholder: '选择资源包规格',
        },
      },
      {
        field: 'remark',
        component: 'InputTextArea',
        label: '备注',
        componentProps: {
          rows: 4,
        },
      },
    ],
    autoFocusFirstItem: true,
    actionColOptions: {
      span: 24,
    },
    labelWidth: 120,
    baseColProps: { span: 20 },
    submitButtonOptions: {
      text: '确认',
    },
    resetButtonOptions: {
      text: '取消',
    },
    submitFunc: async () => {
      const data: IAssignPackageData = await validate();
      const allotment = Number(form.value.allotment);
      if (residue.value < allotment)
        return createMessage.warning(`分配额度不能超出订单额度，请重新选择`);
      setProps({
        submitButtonOptions: {
          loading: true,
        },
      });

      console.log(data, form.value);
      try {
        await AssignPackage({
          tenantId: data.tenantId,
          orderId: data.orderId,
          skuId: data.skuId,
          allotment,
          remark: data.remark,
        });
        setProps({
          submitButtonOptions: {
            loading: false,
          },
        });

        createMessage.success(`分配成功`);
        emit('reload');
        closeModal();
      } catch (error) {
        setProps({
          submitButtonOptions: {
            loading: false,
          },
        });
      }
    },
    resetFunc: async () => {
      closeModal();
    },
  });

  /** 获取分配额度下拉数据 */
  async function getConvertibleSkus(spSpuId: string, spSkuId: string) {
    let res = await ConvertibleSkus({
      spSpuId: spSpuId,
      spSkuId: spSkuId,
    });

    const options = res
      .map((item) => {
        return {
          label: item.attr.proportion.quota.quota,
          value: item.skuId,
          key: item.skuId,
          allotment: Number(item.attr.proportion.quota.quota),
        };
      })
      .sort((item1, item2) => {
        return item1.allotment - item2.allotment;
      });

    updateSchema({
      field: 'skuId',
      componentProps: {
        options: options,
        onChange: async (e, option) => {
          console.log(e, option);
          form.value.allotment = option.allotment;
        },
      },
    });
  }

  const [register, { closeModal }] = useModalInner(async (data) => {
    data.row && setFieldsValue(data.row);

    //获取额度来源订单
    let res = await QueryOrderList();
    const options = (res.records || []).map((item) => {
      let all = Number(item.usage.all);
      let used = Number(item.usage.used);
      return {
        label: item.orderId + `（剩余${all - used}）`,
        value: item.orderId,
        key: item.orderId,
        orderProductInfo: item.orderProductInfo,
        usage: item.usage,
      };
    });

    updateSchema({
      field: 'orderId',
      componentProps: {
        options: options,
        onChange: async (e, option) => {
          console.log(e, option);
          residue.value = Number(option.usage.all) - Number(option.usage.used);
          getConvertibleSkus(option.orderProductInfo.spSpuId, option.orderProductInfo.spSkuId);
        },
      },
    });
  });
</script>

<style lang="less" scoped></style>
